<?php


namespace app\admin\controller;


use app\common\controller\Backend;
use app\common\model\service\Order;
use think\exception\DbException;
use think\response\Json;

class Report extends Backend
{
    protected $relationSearch = true;

    /**
     * CarersApply模型对象
     * @var \app\admin\model\Report
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Report();
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->with(["city","group"])
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list as &$item) {
            $item['reward'] = Order::where('escort_id', $item['id'])->where('status', 4)->sum('commission');
            $item['withdrawals'] = \app\admin\model\UserWithdrawals::where(['user_id' => $item['id'], 'state' => ['in', [0,1]]])->sum('money');
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
}